//
//  RootWebViewController.m
//  MiAiApp
//
//  Created by 徐阳 on 2017/5/18.
//  Copyright © 2017年 徐阳. All rights reserved.
//

#import "RootWebViewController.h"
#import "LEEAlert.h"
#import "ShareView.h"
#import "HEAudioReadingPlayer.h"
#import "HEShareCirlceViewController.h"

@interface RootWebViewController ()<WKNavigationDelegate>

@property (nonatomic,assign) double lastProgress;//上次进度条位置

@property (nonatomic, strong) HEAudioReadingPlayer *audioReadPlayer;

@end

@implementation RootWebViewController


- (void)viewDidLoad {
    [super viewDidLoad];
//    self.statusBarStyle = UIStatusBarStyleDarkContent;
    self.zx_navStatusBarStyle = ZXNavStatusBarStyleDefault;
    [self setupNav];
}

- (void)setupNav {
    //导航栏主题 title文字属性
    UINavigationBar *navBar = self.navigationController.navigationBar;
     //导航栏背景图
     //    [navBar setBackgroundImage:[UIImage imageNamed:@"tabBarBj"] forBarMetrics:UIBarMetricsDefault];
     [navBar setBarTintColor:KWhiteColor];
     [navBar setTintColor:UIColor.blackColor];
     [navBar setTitleTextAttributes:@{NSForegroundColorAttributeName :UIColor.blackColor, NSFontAttributeName : [UIFont systemFontOfSize:18]}];
     
     [navBar setBackgroundImage:[UIImage imageWithColor:KWhiteColor] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
    
    navBar.qmui_borderPosition = QMUIViewBorderPositionBottom;
    navBar.qmui_borderWidth = 1;
    navBar.qmui_borderColor = CSplitLineColor;
    
    
    if (_isShowShare) {
        KWeakSelf
        [self zx_setRightBtnWithImg:IMAGE_NAMED(@"web_more") clickedBlock:^(ZXNavItemBtn * _Nonnull btn) {
            [weakSelf initShareView];
        }];
        self.zx_navRightBtn.zx_fixImageSize = CGSizeMake(24, 24);

        [self zx_setSubRightBtnWithImg:IMAGE_NAMED(@"start_voice") clickedBlock:^(ZXNavItemBtn * _Nonnull btn) {
            weakSelf.audioReadPlayer.hidden = NO;
            [weakSelf.view addSubview:weakSelf.audioReadPlayer];
            
            HEAudioReadModel *model = [[HEAudioReadModel alloc]init];
            model.fileUrl = weakSelf.model.audio;
            model.title = weakSelf.model.info_title;
            [weakSelf.audioReadPlayer player:model];
        }];
        self.zx_navSubRightBtn.zx_fixImageSize = CGSizeMake(26, 24);
        self.zx_navItemMargin = 20;
    }
}

- (void)updateNavigationItems{
    if (_isShowCloseBtn) {
        if (self.webView.canGoBack) {
            self.navigationController.interactivePopGestureRecognizer.enabled = NO;
//            [self addNavigationItemWithImageNames:@[@"back_black",@"close_black"] isLeft:YES target:self action:@selector(leftBtnClick:) tags:@[@2000,@2001]];
//            [self zx_setLeftBtnWithImgName:@"back_black" clickedBlock:^(ZXNavItemBtn * _Nonnull btn) {
//                [super backBtnClicked];
//
//            }];
            
            [self zx_setLeftBtnWithImgName:@"back_black" clickedBlock:^(ZXNavItemBtn * _Nonnull btn) {
                [super backBtnClicked];
            }];
            self.zx_navLeftBtn.zx_fixImageSize = CGSizeMake(17, 17);

            [self zx_setSubLeftBtnWithImgName:@"close_black" clickedBlock:^(ZXNavItemBtn * _Nonnull btn) {
                if (self.presentingViewController) {
                    [self dismissViewControllerAnimated:YES completion:nil];
                }else{
                    [self.navigationController popViewControllerAnimated:YES];
                }
            }];
            
        }else{
            self.navigationController.interactivePopGestureRecognizer.enabled = YES;
            
            //iOS8系统下发现的问题：在导航栏侧滑过程中，执行添加导航栏按钮操作，会出现按钮重复，导致导航栏一系列错乱问题
            //解决方案待尝试：每个vc显示时，遍历 self.navigationController.navigationBar.subviews 根据tag去重
            //现在先把iOS 9以下的不使用动态添加按钮 其实微信也是这样做的，即便返回到webview的第一页也保留了关闭按钮
            
            if (kiOS9Later) {
                [self zx_setLeftBtnWithImgName:@"back_black" clickedBlock:^(ZXNavItemBtn * _Nonnull btn) {
                    [super backBtnClicked];
                }];
                self.zx_navLeftBtn.zx_fixImageSize = CGSizeMake(17, 17);

//                            [self addNavigationItemWithTitles:@[@"返回"] isLeft:YES target:self action:@selector(leftBtnClick:) tags:@[@2001]];
//                [self addNavigationItemWithImageNames:@[@"back_black"] isLeft:YES target:self action:@selector(leftBtnClick:) tags:@[@2001]];
            }
        }
    }
}

- (void)initShareView {
    
      // 初始化分享视图
      CGFloat width = CGRectGetHeight([[UIScreen mainScreen] bounds]) > CGRectGetWidth([[UIScreen mainScreen] bounds]) ? CGRectGetWidth([[UIScreen mainScreen] bounds]) - 20 : CGRectGetHeight([[UIScreen mainScreen] bounds]) - 20;
      
    
    NSArray *arr = @[
        @{@"title" : _model.hasCollect ? @"取消收藏" : @"收藏" , @"image" : @"icon_collection" , @"highlightedImage" : @"icon_collection" , @"type" : [NSNumber numberWithInteger:ShareTypeToCollect]} ,
    @{@"title" : @"微信" , @"image" : @"infor_popshare_weixin_nor" , @"highlightedImage" : @"infor_popshare_weixin_pre" , @"type" : [NSNumber numberWithInteger:ShareTypeToWechat]} ,
    @{@"title" : @"微信朋友圈" , @"image" : @"infor_popshare_friends_nor" , @"highlightedImage" : @"infor_popshare_friends_pre" , @"type" : [NSNumber numberWithInteger:ShareTypeToWechatTimeline]},
//    @{@"title" : @"圈子" , @"image" : @"share_group_select" , @"highlightedImage" : @"share_group_select" , @"type" : [NSNumber numberWithInteger:ShareTypeToCircleRoom]}
    ];

      ShareView *shareView = [[ShareView alloc] initWithFrame:CGRectMake(0, 0, width, 0) InfoArray:arr MaxLineNumber:3 MaxSingleCount:3];
      KWeakSelf
      shareView.openShareBlock = ^(ShareType type){
          if (type == ShareTypeToWechat) {
              [weakSelf wxShare:WXSceneSession];
          }else if (type == ShareTypeToWechatTimeline) {
              [weakSelf wxShare:WXSceneTimeline];
          }else if (type == ShareTypeToCircleRoom) {
              HEShareCirlceViewController *vc = [HEShareCirlceViewController new];
              vc.model = weakSelf.model;
              vc.messageType = HEIMMessageTypeInfoPage;
              [weakSelf.navigationController pushViewController:vc animated:YES];
          }else if (type == ShareTypeToCollect) {
              NSMutableDictionary *dict = @{}.mutableCopy;
              [dict setValue:[NSNumber numberWithInteger:weakSelf.model.id] forKey:@"infoId"];
              [dict setValue:[NSNumber numberWithBool: !weakSelf.model.hasCollect] forKey:@"isCollect"];
              [WOAFNetWorkingHandle POSTNoHUDWithBaseUrl:KServerUrl suffixUrl:KcollectionInfo parameters:dict success:^(id  _Nonnull responseObject) {
                  HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];

                  if (response.success) {
                      [Dialog toastBottom:@"操作成功"];
                      weakSelf.model.hasCollect = !weakSelf.model.hasCollect;
                      if (weakSelf.backBlock) {
                          weakSelf.backBlock();
                      }
                  }
              } failure:^(NSError * _Nonnull error) {
                  
              }];
          }
      };
      
      [LEEAlert actionsheet].config
      .LeeAddCustomView(^(LEECustomView *custom) {
          
          custom.view = shareView;
          
          custom.positionType = LEECustomViewPositionTypeCenter;
      })
      .LeeItemInsets(UIEdgeInsetsMake(0, 0, 0, 0))
      .LeeAddAction(^(LEEAction *action) {
          
          action.type = LEEActionTypeDefault;
          
          action.title = @"取消";
          
          action.titleColor = [UIColor grayColor];
      })
      #ifdef __IPHONE_13_0
      .LeeUserInterfaceStyle(UIUserInterfaceStyleLight)
      #endif
      .LeeShow();
      
}

- (void)leftBtnClick:(UIButton *)btn{
    switch (btn.tag) {
        case 2000:
            [super backBtnClicked];
            
            break;
        case 2001:
        {
            if (self.presentingViewController) {
                [self dismissViewControllerAnimated:YES completion:nil];
            }else{
                [self.navigationController popViewControllerAnimated:YES];
            }
        }
            
            break;
        default:
            break;
    }
}


- (void)wxShare:(int)scene {

    UIImageView *view = [UIImageView new];

    KWeakSelf
    [view sd_setImageWithURL:[NSURL URLWithString:_model.img_url] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
            
        WXMediaMessage *message = [WXMediaMessage message];
        message.title = weakSelf.model.info_title;
        message.description = weakSelf.model.information_brief;
        [message setThumbImage: image];
        
        NSString * file = [NSString stringWithFormat:@"%@/details/#/text?id=%ld", KServerUrl, weakSelf.model.id];

        WXWebpageObject *webpageObject = [WXWebpageObject object];
        webpageObject.webpageUrl = file;
        message.mediaObject = webpageObject;
        
        SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
        req.bText = NO;
        req.message = message;
        // 微信好友
        req.scene = scene;
        
        //唤起微信
        [WXApi sendReq:req completion:^(BOOL success) {
            
        }];
    }];
}

#pragma mark -
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    if (_isShowShare) {
        [self.audioReadPlayer pause];
    }
}

- (void)dealloc{
    
}

#pragma mark -
- (HEAudioReadingPlayer *)audioReadPlayer {
    if (!_audioReadPlayer) {
        _audioReadPlayer = [[HEAudioReadingPlayer alloc] initWithFrame:CGRectMake(30, KScreenHeight - 80 - 30 - ZXSafeAreaBottom, kScreenWidth - 60, 80)];
        [self.view addSubview:_audioReadPlayer];

        _audioReadPlayer.hidden = YES;
    }
    return _audioReadPlayer;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

